package com.ijunfu.spring.di._05_ext.beanPostProcessor;

import com.ijunfu.spring.di._05_ext.annotation.MyResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 *
 * @Title  : 
 * @Author : ijunfu <ijunfu@163.com>
 * @Date   : 2023/11/10 21:56
 * @Version: 1.0
 * @Motto  : 世界很大 世界很小
 *
 */
@Slf4j
@Component
public class MyResourceBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        Class<?> clazz = bean.getClass();

        Arrays.stream(clazz.getDeclaredFields())
                .filter(field -> field.isAnnotationPresent(MyResource.class))
                .forEach(field -> {
                    field.setAccessible(true);

                    String name = field.getName();

                    try {
                        field.set(bean, applicationContext.containsBean(name)?applicationContext.getBean(name):applicationContext.getBean(field.getType()));
                    } catch (IllegalAccessException e) {
                        log.error("set bean error: {}", e.getMessage(), e);
                    }
                });
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
